<?php
/**
 * 出入库、销售记录
 * @package ome_iostocksales
 * @copyright www.shopex.net.cn 2011.3.15
 * @author ome
 */
class ome_iostocksales {
    
    /**
     * 存储出入库、销售记录
     * @access public
     * @param String $data 出入库、销售记录
     * @param String $msg 消息
     * @return boolean 成功or失败
     */
    public function set($data,$io,&$msg,$type=null){
        
        $allow_commit = false;
        kernel::database()->exec('begin');
        $iostock_instance = kernel::service('ome.iostock');
        $sales_instance = kernel::service('ome.sales');
        if ( method_exists($iostock_instance, 'set') ){
            //存储出入库记录
            $iostock_data = $data['iostock'];
            if(!$type){
            	eval('$type='.get_class($iostock_instance).'::LIBRARY_SOLD;');
            }
            
            $iostock_bn = $iostock_instance->get_iostock_bn($type);
            if ( $iostock_instance->set($iostock_bn, $iostock_data, $type, $iostock_msg, $io) ){
                if ( method_exists($sales_instance, 'set') ){
                    //存储销售记录
                    $branch_id = '';
                    if ($data['sales']['sales_items']){
                        foreach ($data['sales']['sales_items'] as $k=>$v){
                            $v['iostock_id'] = $iostock_data[$v['item_detail_id']]['iostock_id'];
                            $data['sales']['sales_items'][$k] = $v;
                        }
                    }
                    $data['sales']['iostock_bn'] = $iostock_bn;
                    $sales_data = $data['sales'];
                    $sale_bn = $sales_instance->get_salse_bn();
                    $sales_data['sale_bn'] = $sale_bn;
                    if ( $sales_instance->set($sales_data, $sales_msg) ){
                        $allow_commit = true;
                    }
                }
            }
        }
        if ($allow_commit == true){
            kernel::database()->commit();
            return true;
        }else{
            kernel::database()->rollBack();
            $msg['instock'] = $iostock_msg;
            $msg['sales'] = $sales_msg;
            return false;
        }
    }
    
    /**
     * 组织出库数据
     * @access public
     * @param String $delivery_id 发货单ID
     * @return sdf 出库数据
     */
    public function get_iostock_data($delivery_id){
        
        $orderObj = &app::get('ome')->model('orders');
        $deliveryObj = &app::get('ome')->model('delivery');
        $delivery_items_detailObj = &app::get('ome')->model('delivery_items_detail');
        
        $iostock_data = array();
        $db = kernel::database();
        //发货单信息
        $sql = 'SELECT `branch_id`,`delivery_bn`,`op_name`,`delivery_time`,`is_cod` FROM `sdb_ome_delivery` WHERE `delivery_id`=\''.$delivery_id.'\'';
        $delivery_detail = $db->selectrow($sql);
        $delivery_items_detail = $delivery_items_detailObj->getList('*', array('delivery_id'=>$delivery_id), 0, -1);
        if ($delivery_items_detail){
            foreach ($delivery_items_detail as $k=>$v){
                $iostock_data[$v['item_detail_id']] = array(
                    'order_id' => $v['order_id'],
                    'branch_id' => $delivery_detail['branch_id'],
                    'original_bn' => $delivery_detail['delivery_bn'],
                    'original_id' => $delivery_id,
                    'original_item_id' => $v['item_detail_id'],
                    'supplier_id' => '',
                    'bn' => $v['bn'],
                    'iostock_price' => $v['price'],
                    'nums' => $v['number'],
                    'cost_tax' => '',
                    'oper' => $delivery_detail['op_name'],
                    'create_time' => $delivery_detail['delivery_time'],
                    'operator' => $delivery_detail['op_name'],
                    'settle_method' => '',
                    'settle_status' => '0',
                    'settle_operator' => '',
                    'settle_time' => '',
                    'settle_num' => '',
                    'settlement_bn' => '',
                    'settlement_money' => '0',
                    'memo' => '',
                );
            }
        }
        return $iostock_data;
    }
    
    /**
     * 组织销售单数据
     * @access public
     * @param String $delivery_id 发货单ID
     * @return sdf 销售单数据
     */
    public function get_sales_data($delivery_id){
        
        $db = kernel::database();
        $sales_items_data = array();
        $sales_data = array();
        $goods_amount = $delivery_cost = $additional_costs = $pkg_remain_money = $discount = $deposit = 0;
        $operator = $order_text = $member_id = $shop_id = $pay_status = '';
        $order_ids = $obj_ids = array();
        
        $iostockObj = &app::get('ome')->model('iostock');
        $ordersObj = &app::get('ome')->model('orders');
        $order_objectsObj = &app::get('ome')->model('order_objects');
        $order_itemsObj = &app::get('ome')->model('order_items');
        $paymentsObj = &app::get('ome')->model('payments');
        $deliveryObj = &app::get('ome')->model('delivery');
        $delivery_orderObj = &app::get('ome')->model('delivery_order');
        $delivery_items_detailObj = &app::get('ome')->model('delivery_items_detail');
        
        $delivery_items_detail = $delivery_items_detailObj->getList('*', array('delivery_id'=>$delivery_id), 0, -1, '`bn`');
        $sql = 'SELECT `logi_id`,`logi_name`,`logi_no`, `branch_id`,`op_name`,`delivery_time` FROM `sdb_ome_delivery` WHERE `delivery_id`=\''.$delivery_id.'\'';
        $delivery_detail = $db->selectrow($sql);
        $branch_id = $delivery_detail['branch_id'];
        $logi_id = $delivery_detail['logi_id'];
        $logi_name = $delivery_detail['logi_name'];
        $logi_no = $delivery_detail['logi_no'];
        
        // 根据delivery_id查出对应的order_id
        $sql = 'SELECT `order_id` FROM `sdb_ome_delivery_order` WHERE `delivery_id`=\''.$delivery_id.'\'';
        $delivery_order = $db->selectrow($sql);
        // 根据order_id查出所有的delivery_id
        $sql = 'SELECT `delivery_id` FROM `sdb_ome_delivery_order` WHERE `order_id`=\''.$delivery_order['order_id'].'\'';
        $order_deliveryids = $db->select($sql);
        $dlys = array();
        if ($order_deliveryids){
            foreach ($order_deliveryids as $dly){
                $dlys[] = $dly['delivery_id'];
            }
        }
        
        //获取订单备注
        $sql = 'SELECT `mark_text` FROM `sdb_ome_delivery_order` as d2o left join sdb_ome_orders as o on d2o.order_id = o.order_id WHERE `delivery_id`=\''.$delivery_id.'\'';
        $order_rows = $db->select($sql);
        $arr_shopping_guide = array();
        foreach($order_rows as $row){
        	if( preg_match_all('/\[D:([^\]]{1,})\]/is', $row['mark_text'],$mathes)){
        		foreach($mathes[1] as $v){
        			$arr_shopping_guide[] = $v;
        		}	
        	}
        } 
        
        //读取出入库记录所对应的订单号
        $iostock_orderids = array();
        $dlys = implode(',', $dlys);
        $sql = "SELECT `original_item_id` FROM `sdb_ome_iostock` WHERE `original_id` IN({$dlys})";
        $iostock_item_ids = kernel::database()->select($sql);
        if ($iostock_item_ids){
            foreach ($iostock_item_ids as $iokey=>$ioval){
                $sql = 'SELECT `order_id` FROM `sdb_ome_delivery_items_detail` WHERE `item_detail_id`=\''.$ioval['original_item_id'].'\'';
                $items_orderids = $db->selectrow($sql);
                $iostock_orderids[] = $items_orderids['order_id'];
            }
        }

        //订单信息
        $sql = 'SELECT is_cod,shop_id,member_id FROM `sdb_ome_orders` WHERE `order_id`=\''.$delivery_order['order_id'].'\'';
        $order_main_detail = $db->selectrow($sql);
        $member_id = $order_main_detail['member_id'];
        $shop_id = $order_main_detail['shop_id'];
        $pay_status = $order_main_detail['is_cod'] == 'false' ? '1' : '0';
        
        // 存储pkg数据
        $pkg = array();
        
        if ($delivery_items_detail){
            foreach ($delivery_items_detail as $k=>$v){
                $order_items = array();
                if ( !in_array($v['order_id'], $iostock_orderids) && !in_array($v['order_id'], $order_ids) ){
                    //订单信息
                    $sql = 'SELECT order_id,is_cod,shop_id,member_id,mark_text,discount,pmt_goods,pmt_order,cost_freight,cost_protect,cost_tax,cost_payment FROM `sdb_ome_orders` WHERE `order_id`=\''.$v['order_id'].'\'';
                    $order_detail = $db->selectrow($sql);
                    
                    //物流费用
                    $delivery_cost += $order_detail['cost_freight'];
                    
                    //附加费：保价费+税金
                    $additional_costs += $order_detail['cost_protect'] + $order_detail['cost_tax'] + $order_detail['cost_payment'];
                    if ($order_detail['discount'] > 0){
                        $additional_costs += $order_detail['discount'];
                    }
                    
                    //预付款:所有为预付款支付方式的支付单总额
                    $sql = 'SELECT sum(money) AS deposit FROM `sdb_ome_payments` WHERE pay_type=\'deposit\' AND order_id=\''.$v['order_id'].'\'';
                    $payments = $db->selectrow($sql);
                    $deposit += $payments['deposit'] ? $payments['deposit'] : 0;
                    
                    //订单折扣费用:订单促销优惠+订单折扣+商品促销优惠
                    $discount += $order_detail['pmt_goods'] + $order_detail['pmt_order'];
                    if ($order_detail['discount'] < 0){
                        $discount += abs($order_detail['discount']);
                    }
                }
                
                // 组织捆绑、礼包等sdf结构数据
                $pkg[$v['order_id']]['order_id'] = $v['order_id'];
                $order_items = array(
                    'item_id' => $v['order_item_id'],
                    'product_id' => $v['product_id'],
                    'bn' => $v['bn'],
                    'number' => $v['number'],
                    'price' => $v['price'],
                    'amount' => $v['amount'],
                );
                if (!in_array($v['order_obj_id'], $obj_ids)){
                    $sql = 'SELECT `obj_type`,`price`,`quantity`,`amount` FROM `sdb_ome_order_objects` WHERE `obj_id`=\''.$v['order_obj_id'].'\'';
                    $objects = $db->selectrow($sql);
                    $pkg[$v['order_id']]['order_objects'][$v['order_obj_id']] = array(
                        'obj_type' => $objects['obj_type'],
                        'price' => $objects['price'],
                        'nums' => $objects['quantity'],
                        'amount' => $objects['amount'],
                    );
                }
                $pkg[$v['order_id']]['order_objects'][$v['order_obj_id']]['order_items'][] = $order_items;
                
                $obj_ids[] = $v['order_obj_id'];
                $order_ids[] = $v['order_id'];
                
                //商品总金额
                $goods_amount += $v['price'] * $v['number'];
                
                //销售单明细
                $sales_items_data[] = array(
                    'item_detail_id' => $v['item_detail_id'],
                    'bn' => $v['bn'],
                    'price' => $v['price'],
                    'nums' => $v['number'],
                    'branch_id' => $branch_id,
                );
            }
        }
        
        // 根据obj_type调用相应的service来获取捆绑、礼包等商品差额
        // 差额 = 捆绑、礼包总金额-捆绑明细总额，小于0增加到订单折扣，大于0增加到附加费,0表示没有差额。
        $difference = 0;
        if ($pkg){
            foreach ($pkg as $orders){
                if ($orders['order_objects']){
                    foreach ($orders['order_objects'] as $obj){
                        if ( $instance = kernel::service('ome.service.order.sales.'.$obj['obj_type']) ){
                            if (method_exists($instance, 'get_difference')){
                                $difference = $instance->get_difference($obj);
                                if ($difference>0){
                                    $additional_costs += $difference;
                                }else{
                                    $discount += $difference;
                                }
                            }
                        }
                    }
                }
            }
        }
        
        //销售单数据
        $sales_data = array(
            'sale_amount' => $goods_amount,
            'delivery_cost' => $delivery_cost,
            'additional_costs' => $additional_costs,
            'deposit' => $deposit,
            'discount' => $discount,
            'memo' => $order_text,
            'member_id' => $member_id,
            'branch_id' => $branch_id,
            'pay_status' => $pay_status,
            'shop_id' => $shop_id,
            'operator' => kernel::single('desktop_user')->get_name(),
            'sale_time' => time(),
            'sales_items' => $sales_items_data,
        	'shopping_guide'=>implode(',', $arr_shopping_guide),
        	'logi_id'=>$logi_id,
	        'logi_name'=>$logi_name,
	        'logi_no'=>$logi_no,
        );
        
        return $sales_data;
    }
    
}